package com.hzit.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import com.alibaba.fastjson.JSON;
import com.ruoyi.system.api.domain.Item;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
@RabbitListener(queues = "hzit-auditgoods")
public class SearchListener {
	@Autowired
	private ElasticsearchClient client;

	@RabbitHandler
	public void getMessage(String message) throws IOException {
		//1. 将获取到的数据转换为List<Item>集合
		List<Item> itemList = JSON.parseArray(message, Item.class);
		System.out.println("itemList = " + itemList);
		//2. 将得到的集合数据放到es中
		BulkRequest.Builder br = new BulkRequest.Builder();
		for (Item item : itemList) {
			String spec = item.getSpec();
			Map map = JSON.parseObject(spec, Map.class);
			item.setSpecMap(map);       // 为specMap字段设置值
			br.operations(op -> op
					.index(idx -> idx.index("item2")
							.id(item.getId() + "")
							.document(item)
					)
			);
		}
		//2.3 执行批量操作
		BulkResponse result = client.bulk(br.build());
		System.out.println("保存到es中数据成功!");
	}
}
